package com.example.myapplication01;

import android.content.ContentUris;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.UriMatcher;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication01.broadcast.AnotherReceiver;
import com.example.myapplication01.broadcast.MyReceiver;
import com.example.myapplication01.cp.MyObserver;
import com.example.myapplication01.service.ForegroundService;
import com.example.myapplication01.service.MyService;

public class MainActivity extends AppCompatActivity {

    // 获取textview组件
    private TextView view;
    private MyReceiver receiver;
    private static final String TAG = "MainActivity";
    private final Handler mHandler = new MyHandler();

    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: view.setText((String) msg.obj);break;
                case 2: view.setText("Hello World!");break;
                default: view.setText("okk");
            }

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.view_model), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.view = findViewById(R.id.textView);


        Runnable task1 = () -> {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = "你好，世界！";
            mHandler.sendMessage(message);
        };
        new Thread(task1).start();
        Runnable task2 = () -> {
            Message message = Message.obtain();
            message.what = 2;
            mHandler.sendMessage(message);
        };
        new Thread(task2).start();
    }

    @NonNull
    private static Uri contentProviderTools(Uri uri) {
        uri = ContentUris.withAppendedId(uri, 1);
        Log.i("LindaMan", uri.toString());

        // UriMatcher
        UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        final int URI_CODE_a = 1;
        final int URI_CODE_b = 2;
        uriMatcher.addURI("com.example.myapplication01", "person/1", URI_CODE_a);
        uriMatcher.addURI("com.example.myapplication01", "person/2", URI_CODE_b);
        switch (uriMatcher.match(uri)) {
            case URI_CODE_a: Log.i("LindaMan", "person1");break;
            case URI_CODE_b: Log.i("LindaMan", "person2");break;
        }
        return uri;
    }

    private void foregroundService() {
        Button btnStart = (Button) findViewById(R.id.btn);
        Button btnStop = (Button) findViewById(R.id.btn2);
        final Intent intent = new Intent(this, ForegroundService.class);


        btnStart.setOnClickListener(v -> {
            intent.putExtra("cmd", 0);// 0,开启前台服务,1,关闭前台服务
            startService(intent);
        });


        btnStop.setOnClickListener(v -> {
            intent.putExtra("cmd", 1);// 0,开启前台服务,1,关闭前台服务
            startService(intent);
        });
    }


    // service
    private void service() {
        Button btn = findViewById(R.id.btn);
        Intent intent = new Intent(this, MyService.class);
        btn.setOnClickListener(v -> {
            intent.putExtra("name", "zhangsan");
            startService(intent);
            stopService(intent);
        });
    }


    // 动态注册广播
    private void registerBroadcast() {
        this.receiver = new MyReceiver();
        AnotherReceiver another = new AnotherReceiver();

        IntentFilter filter1 = new IntentFilter();
        filter1.addAction("com.example.myapplication01.MY_BROADCAST");
        filter1.setPriority(1);
        registerReceiver(this.receiver, filter1);

        IntentFilter filter2 = new IntentFilter();
        filter2.addAction("com.example.myapplication01.MY_BROADCAST");
        filter2.setPriority(2);
        registerReceiver(another, filter2);

        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(v -> {
            Log.d(TAG, "onClick: ");
            Intent intent = new Intent("com.example.myapplication01.MY_BROADCAST");
            /*
             * 如果有许多应用，都静态注册了相同Action的广播，那么一个广播发出，就会导致一批应用启动，极其影响性能和续航
             * 所以安卓在8.0后开始规定，广播如果想要被静态接收器收到，必须在Intent中指定接收器的PackageName和ClassName
             */
            // intent.setComponent(new ComponentName("com.example.myapplication01.broadcast","com.example.myapplication01.broadcast.MyReceiver"));
            sendBroadcast(intent);
        });
    }


    private void toActivity() throws PackageManager.NameNotFoundException {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        String versionName = packageInfo.versionName;
        int versionCode = packageInfo.versionCode;
        System.out.println("versionName: " + versionName + " versionCode: " + versionCode);
    }


    private void show() {
        // 获取button组件
        Button btn = findViewById(R.id.btn);

        btn.setOnClickListener(v -> {
            Toast.makeText(MainActivity.this, view.getText().toString(), Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        getContentResolver().unregisterContentObserver(new MyObserver(new Handler()));
    }
}